package com.vteba.utils.id;

import java.util.Random;
import java.util.UUID;

import com.vteba.utils.common.Numbers;

/**
 * 简单的随机数UUID
 * @author yinlei 
 * @since 2013-12-17
 */
public class UUIDUtils {
    
    public static String uuid() {
        return com.vteba.utils.id.UUID.randomUUID().toString();
    }
    
    private static String digits(long val, int digits) {
    	long hi = 1L << (digits * 4);
    	return Numbers.toString(hi | (val & (hi - 1)), Numbers.MAX_RADIX).substring(1);
    }

    /**
     * 以62进制（字母加数字）生成19位UUID，最短的UUID
     * 
     * @return
     */
    public static String uuid19() {
    	UUID uuid = UUID.randomUUID();
    	StringBuilder sb = new StringBuilder();
    	sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
    	sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
    	sb.append(digits(uuid.getMostSignificantBits(), 4));
    	sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
    	sb.append(digits(uuid.getLeastSignificantBits(), 12));
    	return sb.toString();
    }


    final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
		'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
		'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
		'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
		'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
		'Z' };
    
	/**
	 * 随机ID生成器，由数字、小写字母和大写字母组成
	 * 
	 * @param size
	 * @return
	 */
	public static String id(int size) {
		Random random = new Random();
		char[] cs = new char[size];
		for (int i = 0; i < cs.length; i++) {
			cs[i] = digits[random.nextInt(digits.length)];
		}
		return new String(cs);
	}

}
